import { defineComponent } from 'vue';
import { TaCache, TaToast, TaDataUser, TaPlatform } from '@/utils';

export default defineComponent({
	data() {
		return {
			// 表单数据
			form: <any>{
				type: '',
				phone: '',
				verify: ''
			},
			// 短信验证
			verify: <any>{
				time: 0,
				idxs: 0,
				tips: '获取验证码',
			},
			// 应用名称
			name: <string>import.meta.env.APP_NAME,
			// 同意协议
			agent: <any[]>[true],
			// 显示协议
			showAgreenment: <boolean>false,
			// 图片验证
			showImageVerifyModal: <boolean>false,
		}
	},
	created() {
		// 已登录跳转到首页
		TaDataUser.isLogin() && this.goto.back();
		// 短信发送时间处理
		let timeout = TaCache.get('LoginSmsTimeout') || 0;
		timeout > 0 && this.showTimeout(timeout);
	},
	methods: {
		// 检查表单参数
		checkForm() {
			if (!this.agent[0]) {
				TaToast.error('请同意协议！')
				return false
			}
			if (!/^1\d{10}$/.test(this.form.phone)) {
				TaToast.error('手机号错误！')
				return false
			} else {
				return true
			}
		},
		// 显示拼图验证
		showImageVerify() {
			if (!this.checkForm()) return;
			if (this.verify.time < 1) {
				this.showImageVerifyModal = true
			}
		},
		// 显示倒计时
		showTimeout(time: number) {
			this.verify.time = time
			this.verify.tips = '获取验证码'
			if (this.verify.idxs) {
				clearInterval(this.verify.idxs)
			}
			if (this.verify.time < 1) return
			this.verify.tips = this.verify.time + ' 秒后重试'
			this.verify.idxs = setInterval(() => {
				if (--this.verify.time > 0) {
					this.verify.tips = this.verify.time + ' 秒后重试'
				} else {
					this.showTimeout(0)
				}
				TaCache.set('LoginSmsTimeout', this.verify.time)
			}, 1000)
		},
		// 协议状态切换
		agentChange(state: boolean) {
			this.agent.splice(0, 1, state)
		},
		// 尝试发送短信验证码
		doSend(verify: string) {
			if (!this.checkForm()) return
			if (this.verify.time > 0) {
				return TaToast.error(`请 ${this.verify.time} 秒后重试`)
			}
			// 发送短信验证码
			TaDataUser.verify.send({ phone: this.form.phone, verify: verify }).then((ret: any) => {
				this.showTimeout(ret.data.time), TaToast.success(ret.info)
			}).catch(() => {
				this.verify.time = 0
				this.verify.tips = '获取验证码'
			});
		},
		// 执行注册登录
		doLogin() {
			if (!this.checkForm()) return

			if (!/^\d{6}$/.test(this.form.verify)) {
				TaToast.error('验证码错误！')
				return false
			}

			// 自动识别接口类型
			this.form.type = TaPlatform()
			TaDataUser.login(this.form);
		}
	},
})